if (typeof(TMR_STATUS_BAR_WIDTH) == 'undefined') TMR_STATUS_BAR_WIDTH = 400;
if (typeof(TMR_STATUS_BAR_HEIGHT) == 'undefined') TMR_STATUS_BAR_HEIGHT = 20;
if (typeof(TMR_STATUS_BAR_UPDATE_PERIOD) == 'undefined') TMR_STATUS_BAR_UPDATE_PERIOD = 2; // seconds
var TMR_STATUS_BAR_UPDATER = undefined;

function draw_tmr_status_bar() {
    TMR_STATUS_BAR_ID = 'tmr_status_bar';
    TMR_STATUS_BAR_INNER_ID = 'tmr_status_bar_inner';
    var bar_template = "\
<div id='" + TMR_STATUS_BAR_ID + "'> \
    <div id='" + TMR_STATUS_BAR_INNER_ID + "'></div> \
</div>";
    document.write(bar_template);
    var tmr_status_bar = document.getElementById(TMR_STATUS_BAR_ID);
    var tmr_status_bar_inner = document.getElementById(TMR_STATUS_BAR_INNER_ID);

    tmr_status_bar.style.width = TMR_STATUS_BAR_WIDTH + 3 + 'px';
    tmr_status_bar.style.height = TMR_STATUS_BAR_HEIGHT + 'px';
    tmr_status_bar.style.border = '1px solid silver';

    tmr_status_bar_inner.style.width = '0px';
    tmr_status_bar_inner.style.height = TMR_STATUS_BAR_HEIGHT - 6 + 'px';
    tmr_status_bar_inner.style.margin = '3px';
    tmr_status_bar_inner.style.background = 'silver'
};

function calc_tmr_status_bar_percent(started_at, now, length) {
    var played_time = now - started_at;
    return played_time / length;
};

function set_tmr_status_bar_progress(percent) {
    if (percent > 1) percent = 1;
    width = TMR_STATUS_BAR_WIDTH * percent;
    var tmr_status_bar_inner = document.getElementById(TMR_STATUS_BAR_INNER_ID);
    tmr_status_bar_inner.style.width = width + 'px';
};

function update_tmr_status_bar_progress(data) {
    var started_at = data.last_played;
    var now = data.current_ts;
    var length = data.length;
    var percent = calc_tmr_status_bar_percent(started_at, now, length);
    set_tmr_status_bar_progress(percent);
};

function start_auto_update_tmr_status_bar(data) {
    var started_at = data.last_played;
    var now = data.current_ts;
    var length = data.length;

    var estimate = parseInt(started_at + length - now);
    var steps = parseInt(estimate / TMR_STATUS_BAR_UPDATE_PERIOD);
    var percent = calc_tmr_status_bar_percent(started_at, now, length);
    var progress_step = (1 - percent) / steps;
    clearInterval(TMR_STATUS_BAR_UPDATER);
    TMR_STATUS_BAR_UPDATER = setInterval(
        function(){ 
            shift_tmr_status_bar_progress(progress_step);
        },
        TMR_STATUS_BAR_UPDATE_PERIOD * 1000
    );
};

function get_tmr_status_bar_progress() {
    var tmr_status_bar_inner = document.getElementById(TMR_STATUS_BAR_INNER_ID);
    return parseInt(tmr_status_bar_inner.style.width) / TMR_STATUS_BAR_WIDTH
};

function shift_tmr_status_bar_progress(delta) {
    // console.log('shift_tmr_status_bar_progress ' + delta);
    var percent = get_tmr_status_bar_progress();
    set_tmr_status_bar_progress(percent + delta);
};

function get_unix_time() {
    return parseInt((new Date).getTime() / 1000);
};

draw_tmr_status_bar();